package pku;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * 这是一个消息队列的内存实现
 */
public class MessageStoreIn {

    static FileInputStream is = null;
    static FileChannel fi = null;
    static ByteBuffer buffer = null;
    static int i4 = 0;
    // 消息存储
    static HashMap<String, ArrayList<ByteMessage>> msgs = new HashMap<>();

    static {

        try {
            is = new FileInputStream("./data/a.txt");
            fi = is.getChannel();
            buffer = ByteBuffer.allocate(2048);
            StringBuilder sb = new StringBuilder();
            buffer.clear();
            while (fi.read(buffer) != -1) {
                buffer.flip();
                byte[] bytes = buffer.array();
                String str = new String(bytes);
                buffer.clear();
                sb.append(str);
            }
            System.out.println(sb);
            String[] sss = (sb.toString()).split(" ");
            for (String st : sss) {
                System.out.println(st);

                i4++;
                System.out.println("读入" + i4);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    static final MessageStoreIn store = new MessageStoreIn();

    // 遍历指针
    HashMap<String, Integer> readPos = new HashMap<>();

    // 加锁保证线程安全
    public synchronized ByteMessage pull(String queue, String topic) {
        String k = queue + " " + topic;
        if (!readPos.containsKey(k)) {
            readPos.put(k, 0);
        }
        int pos = readPos.get(k);
        if (!msgs.containsKey(topic)) {
            return null;
        }

        ArrayList<ByteMessage> list = msgs.get(topic);
        if (list.size() <= pos) {
            return null;
        } else {
            ByteMessage msg = list.get(pos);
            // 将键k的值+1，表示当前读到第pos个msg，下一次应该读+1个
            readPos.put(k, pos + 1);
            return msg;
        }
    }
}
